import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/custom_appbar.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/utils/event_bus.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/widget/status_btn.dart';
import '../../http/api.dart';
import '../../http/http_utils.dart';
import '../../res/w_colors.dart';
import '../../res/w_dimens.dart';
import '../../utils/router_helper.dart';
import '../../widget/w_toast.dart';
import 'alert_msg_page.dart';
import 'notice_msg_page.dart';

class MsgPage extends StatefulWidget {
  const MsgPage({super.key});

  @override
  State<MsgPage> createState() => _MsgPageState();
}

class _MsgPageState extends State<MsgPage> {
  late final PageController _pageController = PageController();
  int _currentPageIndex = 0;
  List<Map> msgList = [
    {
      "title": "通知公告",
      "count": 0,
      "color": Colors.green,
      "icon": Icons.volume_up, // 添加了 icon 键
    },
    {
      "title": "提醒消息",
      "color": Colors.blue,
      "icon": Icons.notifications_on_sharp, // 添加了 icon 键
      "count": 0,
    },
  ];
  var bus = EventBus();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          CustomAppBar(
            leftWidget: const SizedBox(),
            contentTitle: "消息",
          ),
          Expanded(
            child: RefreshIndicator(
              onRefresh: getUnreadCount,
              child: ListView.builder(
                padding: EdgeInsets.zero,
                //shrinkWrap: true,
                itemCount: msgList.length,
                //预留接口，这里动态的传值
                itemBuilder: _buildMessageCard,
              ),
            ),
          )
        ],
      ),
    );
  }

  // 构建单个消息卡片的函数
  Widget _buildMessageCard(context, index) {
    Map item = msgList[index];
    return GestureDetector(
        onTap: () {
          // print("点击点击点击");
          _currentPageIndex = index;
          //先暂时写跳转到首页点击事件
          _currentPageIndex == 0
              ? RouteHelper.pushWidget(context, const NoticeMsgPage())
                  .then((value) {
                  getUnreadCount();
                })
              : RouteHelper.pushWidget(context, const AlertMsgPage())
                  .then((value) {
                  getUnreadCount();
                });
        },
        child: Container(
          alignment: Alignment.center,
          margin: EdgeInsets.only(left: 15.px, right: 15.px, top: 10.px),
          padding: EdgeInsets.symmetric(
              horizontal: WDimens.tsLarge, vertical: WDimens.tsXXXXLarge),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10.px),
              color: Colors.white,
              boxShadow: const [
                BoxShadow(
                    color: WColors.border, offset: Offset(0, 1), blurRadius: 2)
              ]),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              CircleAvatar(
                backgroundColor: item["color"],
                child: Icon(item["icon"], color: Colors.white),
              ),
              SizedBox(
                width: WDimens.tsXXLarge,
              ),
              Expanded(
                  child: Column(
                mainAxisAlignment: MainAxisAlignment.center, // 垂直方向从顶部开始
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    item["title"],
                    style: TextStyle(
                      color: WColors.mainTextColor,
                      fontSize: WDimens.tsLarge,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(
                    item["count"] != 0 ? "未读消息：${item["count"]}" : "暂无新消息",
                    style: TextStyle(
                      color: WColors.hintTextColor,
                      fontSize: WDimens.tsLabel,
                    ),
                  ),
                ],
              )),
              Offstage(
                offstage: item["count"] == 0,
                child: StatusBtn(
                  width: 10.px,
                  height: 10.px,
                  radius: 8.px,
                  isItemBtn: true,
                  isBg: true,
                  color: WColors.redMain,
                  margin: EdgeInsets.only(right: 5.px),
                ),
              ),
              Icon(
                Icons.arrow_forward_ios,
                size: WDimens.tsLarge, // 根据需要调整图标大小
                color: WColors.hintTextColor, // 根据需要调整图标颜色
              ),
            ],
          ),
        ));
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getUnreadCount();
    bus.on("noticeReadCount", (arg) {
      msgList[0]["count"] = arg?['notNum'] ?? 0;
      msgList[1]["count"] = arg?['taskNum'] ?? 0;
      int count = msgList[0]["count"] + msgList[1]["count"];
      bus.emit("unReadCount", count);
      setState(() {});
    });
  }

  Future<Null> getUnreadCount() async {
    HttpUtils()
        .get(
            "${Api.getNoticeMessageCount}?userId=${WConstant().userInfo.userId}")
        .then((value) {
      if (value.resultCode == 200 && value.data["resultCode"] == 200) {
        var msgCount = value.data["data"];
        msgList[0]["count"] = msgCount?['notNum'] ?? 0;
        msgList[1]["count"] = msgCount?['taskNum'] ?? 0;
        int count = msgList[0]["count"] + msgList[1]["count"];
        bus.emit("unReadCount", count);
        setState(() {});
      } else {
        Toast.toast(value.errMsg ?? "");
      }
    }).catchError((e) {});
  }
}
